﻿Imports Newtonsoft.Json.JsonConvert
Public Class SettingsWindow

#Region "Variables"
    Dim actived As Boolean
    Dim fonts As New Dictionary(Of String, Font)
    Dim highlight As List(Of TranslatorIO.HighlightGroup)
    Dim source_language As String = ""
    Dim target_language As String = ""
#End Region

#Region "UI Language"
    Sub New()

#Region "This call is required by the designer."
        actived = False
        InitializeComponent()
        actived = True
#End Region

#Region "Set fonts"
        Dim generalFont As Font = New FontConverter().ConvertFromString(Language("fonts", "general"))
        Dim titleFont As Font = New FontConverter().ConvertFromString(Language("fonts", "title"))
        Me.Font = generalFont
        Button12.Font = titleFont
        Button13.Font = titleFont
        Button14.Font = titleFont
        Button15.Font = titleFont
        GroupBox1.Font = titleFont
        TableLayoutPanel12.Font = generalFont
#End Region

#Region "Set right to left"
        Me.RightToLeft = R2L
        Me.RightToLeftLayout = R2L
        Me.TabControl1.RightToLeft = R2L
        Me.TabControl1.RightToLeftLayout = R2L
        Me.TextBox2.RightToLeft = RightToLeft.No
        Me.TextBox3.RightToLeft = RightToLeft.No
#End Region

#Region "Set window words"
        'Basic
        Me.Text = Language("settings", "title")
        TabPage1.Text = Language("settings", "tab_fonts")
        TabPage2.Text = Language("settings", "tab_highlights")
        TabPage3.Text = Language("settings", "tab_translation")
        Button1.Text = Language("settings", "save")
        Button2.Text = Language("settings", "cancel")
        'Fonts
        Label1.Text = Language("settings_fonts", "general")
        Label2.Text = Language("settings_fonts", "title")
        Label3.Text = Language("settings_fonts", "menu")
        Label4.Text = Language("settings_fonts", "small")
        Label5.Text = Language("settings_fonts", "msg_content")
        Label6.Text = Language("settings_fonts", "msg_buttons")
        Label7.Text = Language("settings_fonts", "welcome_general")
        Label8.Text = Language("settings_fonts", "welcome_large")
        Label9.Text = Language("settings_fonts", "welcome_small")
        'Highlights
        Label10.Text = Language("settings_highlights", "name")
        Label11.Text = Language("settings_highlights", "extensions")
        Label12.Text = Language("settings_highlights", "rules")
        Label13.Text = Language("settings_highlights", "expression")
        Label14.Text = Language("settings_highlights", "excample")
        Button12.Text = Language("settings_highlights", "add")
        Button13.Text = Language("settings_highlights", "remove")
        Button14.Text = Language("settings_highlights", "rules_add")
        Button15.Text = Language("settings_highlights", "rules_remove")
        Button16.Text = Language("settings_highlights", "color")
        Button17.Text = Language("settings_highlights", "backcolor")
        'Translation
        GroupBox1.Text = Language("settings_translation", "google_translate")
        Label15.Text = Language("settings_translation", "source_language")
        Label16.Text = Language("settings_translation", "target_language")
#End Region

    End Sub
    Private Sub ListBox1_DrawItem(sender As Object, e As DrawItemEventArgs) Handles ListBox1.DrawItem, ListBox2.DrawItem
        e.DrawBackground()
        e.DrawFocusRectangle()
        If e.Index = -1 Then Return
        Using sf As New StringFormat
            Dim rect = e.Bounds
            Dim text = sender.Items(e.Index)
            Dim size = TextRenderer.MeasureText(text, e.Font)
            rect.Height = size.Height
            If sender.RightToLeft = RightToLeft.Yes Then sf.FormatFlags = StringFormatFlags.DirectionRightToLeft
            e.Graphics.DrawString(text, e.Font, New SolidBrush(e.ForeColor), rect, sf)
        End Using
    End Sub
#End Region

#Region "Functions"
    Sub loadFonts()
        fonts.Clear()
        For Each item In {"general", "title", "menu", "small", "message", "message_btn", "welcome", "welcome_large", "welcome_small"}
            fonts.Add(item, New FontConverter().ConvertFromString(Language("fonts", item)))
        Next
    End Sub
    Sub loadHighlights()
        ListBox1.Items.Clear()
        For Each item In highlight
            ListBox1.Items.Add(Language("settings_highlights", "highlight_" & item.Name, item.Name))
        Next
    End Sub
    Sub loadLanguages()
        Dim json As String = "{'sq':'shqip','ar':'العربية','am':'አማርኛ','az':'azərbaycan','ga':'Gaeilge','et':'eesti','or':'ଓଡ଼ିଆ','eu':'euskara','be':'беларуская','bg':'български','is':'íslenska','pl':'polski','bs':'bosanski','fa':'فارسی','af':'Afrikaans','tt':'татар','da':'Dansk','de':'Deutsch','ru':'Русский','fr':'Français','tl':'Filipino','fi':'Suomi','fy':'Frysk','km':'ខ្មែរ','ka':'ქართული','gu':'ગુજરાતી','kk':'қазақ тілі','ht':'Haitian Creole','ko':'한국어','ha':'هَوُسَ','nl':'Nederlands','ky':'кыргызча','gl':'galego','ca':'català','cs':'Čeština','kn':'ಕನ್ನಡ','co':'Corsican','hr':'Hrvatski','ku':'kurdî','la':'Latin','lv':'latviešu','lo':'ລາວ','lt':'lietuvių','lb':'Lëtzebuergesch','rw':'Ikinyarwanda','ro':'română','mg':'Malagasy','mt':'Malti','mr':'मराठी','ml':'മലയാളം','ms':'Melayu','mk':'македонски','mi':'te reo Māori','mn':'монгол','bn':'বাংলা','my':'မြန်မာ','hmn':'Hmong','xh':'isiXhosa','zu':'isiZulu','ne':'नेपाली','no':'norsk','pa':'ਪੰਜਾਬੀ','pt':'Português (Portugal)','ps':'پښتو','ny':'Nyanja','ja':'日本語','sv':'Svenska','sm':'Samoan','sr':'српски','st':'Sesotho','si':'සිංහල','eo':'esperanto','sk':'Slovenčina','sl':'slovenščina','sw':'Kiswahili','gd':'Gàidhlig','ceb':'Binisaya','so':'Soomaali','tg':'тоҷикӣ','te':'తెలుగు','ta':'தமிழ்','th':'ไทย','tr':'Türkçe','tk':'Türkmen','cy':'Cymraeg','ug':'ئۇيغۇرچە','ur':'اردو','uk':'Українська','uz':'o‘zbek','es':'Español','iw':'עברית','el':'Ελληνικά','haw':'ʻŌlelo Hawaiʻi','sd':'سنڌي','hu':'magyar','sn':'chiShona','hy':'հայերեն','ig':'Asụsụ Igbo','it':'Italiano','yi':'ייִדיש','hi':'हिन्दी','su':'Basa Sunda','id':'Indonesia','jw':'Jawa','en':'English','yo':'Èdè Yorùbá','vi':'Tiếng Việt','zh-CN':'简体中文'}"
        Dim languages As Dictionary(Of String, String) = DeserializeObject(Of Dictionary(Of String, String))(json)

        Dim table As New DataTable()
        table.Columns.Add("key")
        table.Columns.Add("value")

        If languages IsNot Nothing Then
            For Each item In languages
                table.Rows.Add({item.Key, Language("settings_translation", "language_" & item.Key) & " - " & item.Value})
            Next
            table.DefaultView.Sort = "key ASC"
            table = table.DefaultView.ToTable()

            Dim row As DataRow = table.NewRow()
            row.ItemArray = {"auto", Language("settings_translation", "language_auto")}
            table.Rows.InsertAt(row, 0)
        End If

        ComboBox1.ValueMember = "key"
        ComboBox1.DisplayMember = "value"
        ComboBox1.DataSource = table.Copy()

        table.Rows.RemoveAt(0)
        ComboBox2.ValueMember = "key"
        ComboBox2.DisplayMember = "value"
        ComboBox2.DataSource = table

        Dim info = getTranslateInfo()
        source_language = info.Key
        target_language = info.Value
        ComboBox1.SelectedValue = info.Key
        ComboBox2.SelectedValue = info.Value
    End Sub
    Function getFontText(font As Font) As String
        Dim name As String = font.Name
        Dim size As Single = font.Size
        Dim style As String = ""
        Select Case font.Style
            Case FontStyle.Bold : style = Language("settings_fonts", "font_bold")
            Case FontStyle.Italic : style = Language("settings_fonts", "font_italic")
            Case FontStyle.Regular : style = Language("settings_fonts", "font_regular")
            Case FontStyle.Bold Or FontStyle.Italic : style = Language("settings_fonts", "font_bold_italic")
            Case Else : style = font.Style.ToString
        End Select

        Return String.Format(Language("settings_fonts", "font_text"), name, size, style)
    End Function
#End Region

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Call loadFonts()

        Button3.Text = getFontText(fonts("general"))
        Button4.Text = getFontText(fonts("title"))
        Button5.Text = getFontText(fonts("menu"))
        Button6.Text = getFontText(fonts("small"))
        Button7.Text = getFontText(fonts("message"))
        Button8.Text = getFontText(fonts("message_btn"))
        Button9.Text = getFontText(fonts("welcome"))
        Button10.Text = getFontText(fonts("welcome_large"))
        Button11.Text = getFontText(fonts("welcome_small"))

        highlight = Highlights.ToList()
        Call loadHighlights()

        ListBox1_SelectedIndexChanged(ListBox1, EventArgs.Empty)

        Call loadLanguages()
    End Sub

    Private Sub Fonts_Click(sender As Object, e As EventArgs) Handles Button3.Click, Button9.Click, Button8.Click, Button7.Click, Button6.Click, Button5.Click, Button4.Click, Button11.Click, Button10.Click
        FontDialog1.Font = fonts(sender.Tag)
        If FontDialog1.ShowDialog() = DialogResult.OK Then
            sender.Text = getFontText(FontDialog1.Font)
            fonts(sender.Tag) = FontDialog1.Font
        End If
    End Sub

    Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
        actived = False
        TextBox1.Clear()
        TextBox2.Clear()
        TextBox3.Clear()
        ListBox2.Items.Clear()
        Label14.BackColor = Color.Transparent
        Label14.ForeColor = SystemColors.ControlText
        TableLayoutPanel5.Enabled = ListBox1.SelectedIndex > -1
        Button13.Enabled = ListBox1.SelectedIndex > -1
        actived = True
        If ListBox1.SelectedIndex = -1 Then Return

        With highlight(ListBox1.SelectedIndex)
            actived = False
            TextBox1.Text = Language("settings_highlights", "highlight_" & .Name, .Name)
            TextBox2.Text = Join(.Extensions.ToArray, ";")
            ListBox2.Items.Clear()
            For i = 1 To .Rules.Count
                ListBox2.Items.Add(String.Format(Language("settings_highlights", "highlight_rule_item"), i))
            Next
            If .Rules.Count > 0 Then ListBox2.SelectedIndex = 0
            actived = True
        End With

        ListBox2_SelectedIndexChanged(ListBox2, EventArgs.Empty)
    End Sub
    Private Sub ListBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox2.SelectedIndexChanged
        actived = False
        TextBox3.Clear()
        Label14.BackColor = Color.Transparent
        Label14.ForeColor = SystemColors.ControlText
        Button15.Enabled = ListBox2.SelectedIndex > -1
        TextBox3.Enabled = ListBox2.SelectedIndex > -1
        Button16.Enabled = ListBox2.SelectedIndex > -1
        Button17.Enabled = ListBox2.SelectedIndex > -1
        actived = True
        If ListBox2.SelectedIndex = -1 Then Return

        With highlight(ListBox1.SelectedIndex).Rules(ListBox2.SelectedIndex)
            actived = False
            TextBox3.Text = .Pattern
            Label14.ForeColor = .Color
            Label14.BackColor = .BackColor
            actived = True
        End With
    End Sub

    Private Sub Button12_Click(sender As Object, e As EventArgs) Handles Button12.Click
        highlight.Add(New TranslatorIO.HighlightGroup(Language("settings_highlights", "highlight_new"), ".*"))
        Call loadHighlights()
        ListBox1.SelectedIndex = ListBox1.Items.Count - 1
    End Sub
    Private Sub Button13_Click(sender As Object, e As EventArgs) Handles Button13.Click
        Dim index1 As Integer = ListBox1.SelectedIndex
        If index1 > -1 Then
            highlight.RemoveAt(index1)
            Call loadHighlights()
            ListBox1.SelectedIndex = -1
            ListBox1_SelectedIndexChanged(ListBox1, EventArgs.Empty)
        End If
    End Sub
    Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
        Dim index1 As Integer = ListBox1.SelectedIndex
        If index1 > -1 AndAlso actived Then highlight(index1).Name = TextBox1.Text
    End Sub
    Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged
        Dim index1 As Integer = ListBox1.SelectedIndex
        If index1 > -1 AndAlso actived Then highlight(index1).Extensions = Trim(TextBox2.Text).Split(SplitStr.Replace(".", "").Replace("*", "").ToCharArray, StringSplitOptions.RemoveEmptyEntries).ToList
    End Sub

    Private Sub Button14_Click(sender As Object, e As EventArgs) Handles Button14.Click
        Dim index1 As Integer = ListBox1.SelectedIndex
        If index1 > -1 Then
            highlight(index1).Rules.Add(New TranslatorIO.HighlightRule())
            Call ListBox1_SelectedIndexChanged(ListBox1, EventArgs.Empty)
            ListBox2.SelectedIndex = ListBox2.Items.Count - 1
        End If
    End Sub
    Private Sub Button15_Click(sender As Object, e As EventArgs) Handles Button15.Click
        Dim index1 As Integer = ListBox1.SelectedIndex
        Dim index2 As Integer = ListBox2.SelectedIndex

        If index1 > -1 AndAlso index2 > -1 Then
            highlight(index1).Rules.RemoveAt(index2)
            Call ListBox1_SelectedIndexChanged(ListBox1, EventArgs.Empty)
            ListBox2.SelectedIndex = -1
        End If
    End Sub
    Private Sub TextBox3_TextChanged(sender As Object, e As EventArgs) Handles TextBox3.TextChanged
        Dim index1 As Integer = ListBox1.SelectedIndex
        Dim index2 As Integer = ListBox2.SelectedIndex

        If index1 > -1 AndAlso index2 > -1 AndAlso actived Then
            highlight(index1).Rules(index2).Pattern = TextBox3.Text
        End If
    End Sub
    Private Sub Button16_Click(sender As Object, e As EventArgs) Handles Button16.Click
        Dim index1 As Integer = ListBox1.SelectedIndex
        Dim index2 As Integer = ListBox2.SelectedIndex

        If index1 > -1 AndAlso index2 > -1 Then
            ColorDialog1.Color = highlight(index1).Rules(index2).Color
            If ColorDialog1.ShowDialog = DialogResult.OK Then
                highlight(index1).Rules(index2).Color = ColorDialog1.Color
                Label14.ForeColor = ColorDialog1.Color
            End If
        End If
    End Sub
    Private Sub Button17_Click(sender As Object, e As EventArgs) Handles Button17.Click
        Dim index1 As Integer = ListBox1.SelectedIndex
        Dim index2 As Integer = ListBox2.SelectedIndex

        If index1 > -1 AndAlso index2 > -1 Then
            ColorDialog1.Color = highlight(index1).Rules(index2).BackColor
            If ColorDialog1.ShowDialog = DialogResult.OK Then
                highlight(index1).Rules(index2).BackColor = ColorDialog1.Color
                Label14.BackColor = ColorDialog1.Color
            End If
        End If
    End Sub

    Private Sub ComboBox1_SelectedValueChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedValueChanged
        source_language = ComboBox1.SelectedValue
    End Sub
    Private Sub ComboBox2_SelectedValueChanged(sender As Object, e As EventArgs) Handles ComboBox2.SelectedValueChanged
        target_language = ComboBox2.SelectedValue
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim converter As New FontConverter
        For Each item In fonts
            'New FontConverter().ConvertFromString(Language("fonts", item))
            Language.EditSetting("fonts", item.Key, converter.ConvertToString(item.Value), True, False)
        Next
        Language.SaveSettings()

        Highlights = highlight
        Config.EditSetting("info", "highlight", SerializeObject(Highlights))

        Config.EditSetting("settings", "source_language", source_language)
        Config.EditSetting("settings", "target_language", target_language)
    End Sub

End Class